// 各个依赖包
const express = require('express')
const createError = require('http-errors')
const path = require('path')
const cookieParser = require('cookie-parser')
const morgan = require('morgan')
const logger = require('./logger')
const cors = require('cors')
var bodyParser = require ('body-parser')
// 导入路由文件
const indexRouter = require('./routes/index');
// const usersRouter = require('./routes/users')


// Express 引用实例化
const app = express()
app.use(cors());

// 视图模版设置
app.set('views',path.join(__dirname,'views'))
app.set('view engine', 'jade')


const port = 3000
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }));
// 日志打印
app.use(indexRouter)

app.use(morgan('dev'))
// 使用对post来的数据json格式化
app.use(express.json());

// 捕捉404错误
app.use(function (req, res, next) {
    next(createError(404));
})

const _errorHandler = (err, req, res, next) => {
    //错误日志打印
    logger.error(`${req.method} ${req.originalUrl}` + err.message)
    const errorMsg = err.message
    res.status(err.status || 500).json({
        status:err.status,
        code: -1,
        success: false,
        message: errorMsg,
        data:{}
    })
}
app.use(_errorHandler)
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})